/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期: 2020年1月4日
 */
package com.massyframework.beanskin.runtime.service.web.jasper;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.massyframework.beanskin.util.classloading.ClassLoaderUtils;
import com.massyframework.beanskin.web.ModularHttpProcessor;
import com.massyframework.beanskin.web.ModularServletContext;

/**
 * {@link JasperResourceProcessor} 提供对jsp资源的http请求处理
 */
final class JasperResourceProcessor extends ModularHttpProcessor {

    private static Set<String> EXTENSION_NAMES =
            new HashSet<String>(Arrays.asList(
                    ".jsp", ".jspf", ".jspx", ".xsp", ".JSP", ".JSPF", ".JSPX", ".XSP"));
    private Servlet jspServlet;
    private ClassLoader classLoader;


    /**
     * 构造方法
     */
    public JasperResourceProcessor() {
    }

    /**
     * 初始化
     * @throws ServletException 初始化阶段发生非预期的例外
     */
    @Override
    protected void init() throws ServletException {
        super.init();
        ModularServletContext context = this.getModularServletContext();
        this.classLoader = context != null ?
            context.getAssociatedModule().getModuleClassLoader() :
                Thread.currentThread().getContextClassLoader();

        ClassLoader contextLoader =
             ClassLoaderUtils.setThreadContextClassLoader(this.classLoader);
        try {
            String className = "org.apache.jasper.servlet.JspServlet";
        	Class<?> clazz = this.getClass().getClassLoader().loadClass(className);

            this.jspServlet = Servlet.class.cast(clazz.getDeclaredConstructor().newInstance());
            this.jspServlet.init(
                    new ConfigImpl(this.getServletConfig().getServletContext()));
        }catch(Exception e) {
            throw new ServletException(e.getMessage(), e);
        }finally {
            ClassLoaderUtils.setThreadContextClassLoader(contextLoader);
        }
    }



    /**
     * 处理Http请求，并填充Http响应
     *
     * @param request  {@link HttpServletResponse}, http请求
     * @param response {@link HttpServletResponse}, http响应
     * @return {@link boolean}, 返回<code>true</code>表示已处理该请求，否则返回<code>false</code>
     * @throws ServletException 请求处理阶段发生的非预期例外
     * @throws IOException io读写发生的非预期例外
     */
    @Override
    public boolean process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (!this.isJspPage(pathInfo)){
            return false;
        }

        RequestURIRewriteHttpServletRequest req = 
        		new RequestURIRewriteHttpServletRequest(request, this.getServletConfig().getServletContext());
        ClassLoader contextLoader =
        		ClassLoaderUtils.setThreadContextClassLoader(this.classLoader);
        try {
	        this.jspServlet.service(req, response);
	        return true;
        }finally {
        	ClassLoaderUtils.setThreadContextClassLoader(contextLoader);
        }
    }

    /**
     * 判断资源是否jsp页面
     * @param pathInfo 路径
     * @return {@link boolean},返回<code>true</code>表示是需要jsp页面
     */
    protected boolean isJspPage(String pathInfo) {
        if (pathInfo == null) return false;

        int pos = pathInfo.lastIndexOf(".");
        if (pos == -1) return false;

        String ext = pathInfo.substring(pos);
        return EXTENSION_NAMES.contains(ext);
    }

    /**
     * 析构释放资源
     */
    @Override
    public void destroy() {
        if (this.jspServlet != null) {
            this.jspServlet.destroy();
            this.jspServlet = null;
        }
        super.destroy();
    }

    private class ConfigImpl implements ServletConfig {

        private ServletContext context;
        private Map<String, String> initParams;

        public ConfigImpl(ServletContext context){
            this.context = context;
            Map<String, String> map= new HashMap<String, String>();
            map.put("logVerbosityLevel", "DEBUG");
            map.put("fork", "false");
            map.put("xpoweredBy", "false");
            map.put("compilerSourceVM", "1.7");
            map.put("compilerTargetVM", "1.7");
            map.put("logVerbosityLevel", "DEBUG");
            this.initParams = Collections.unmodifiableMap(map);
        }


        @Override
        public String getServletName() {
            return "jsp";
        }

        @Override
        public ServletContext getServletContext() {
            return this.context;
        }

        @Override
        public String getInitParameter(String name) {
            return this.initParams.get(name);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return Collections.enumeration(this.initParams.keySet());
        }
    }
}
